import os
import os.path
import shutil
from Filexporter.models import Folder

class file_explorer:

    def __init__(self,srcdir,dstdir):
        self.srcdir = srcdir
        self.dstdir = dstdir

    def MoveFolder(self):
        for foldernames in os.listdir(self.srcdir):
            query = Folder.objects.filter(subfolder=foldernames)
            if query:
                try:
                    sub_folder = Folder.objects.get(subfolder=foldernames)
                    par_folder = sub_folder.parentfolder
                except Exception as e:
                    print e

                src_path = self.srcdir + '/' + foldernames
                dst_path = self.dstdir + '/' + par_folder + '/' + foldernames
                print 'src folder is :' + src_path + '  dst folder is:' + dst_path
                if not os.path.exists(str(dst_path)):
                   print 'dst folder transfer' + foldernames
                   try:
                      shutil.copytree(str(src_path),str(dst_path))
                      u = Folder.objects.filter(subfolder=foldernames)
                      u.update(is_copy='True')
                   except IOError as e:
                      print e
                else:
                    print 'dst folder is exist' + foldernames

    def FetchFiles(self):
        List = Folder.objects.order_by('parentfolder').distinct('parentfolder')
        for sublist in List:
            for file in sublist:
                print file





if __name__ == "__main__":
    srcdir = "/root/old"
    dstdir = "/root/new"
    file_explorer01 = file_explorer(srcdir,dstdir)
